// pages/driver/personalInformation/personalInformation.js
const citylist = require("../../../data/PCA.js");
const handler = require("../../../utils/function.js");
var app = getApp(),
    api = require("../../../api.js");
console.log(citylist);
Page({
    /**
     * 页面的初始数据
     */
    data: {
      img: handler.driverImg,
        driverAge: "请选择",
        arrayDriverAge: [],
        driver: { //所有信息验证
            city: ['吉林省','长春市','双阳区'],
            city_status: false,
            cityTest: false,
            name: null,
            name_status: false,
            nameTest: false,
            phone: null,
            phone_status: false,
            phoneTest: false,
            id: null,
            id_status: false,
            idTest: false,
            relative: null,
            relative_status: false,
            relativeTest: false,
            bank: null,
            bank_status: false,
            bankTest: false,
            workTime: -1,
            workTime_status: false,
            workTimeTest: false,
            idCard: null,
            idCard_status: false,
            idCardTest: false,
            driver: null,
            driver_status: false,
            driverTime_start:'',
            driverTime_end: '',
            driverTime_status: false,
            driverTimeTest: false,
            idCardPhoto: '',
            idCardPhotoTest: '',
            driverPhoto: '',
            driverPhotoTest: '',
            xszz: '',
            xszf: '',
            jkd:'',
            yyzgz:'',
            czczp:'',
            clzp:'',
            cateindex:-1,
            arrayDrivercate:["代驾","出租车"]
        },
        url_type: "",
        driverEffictTime: ["6年", "10年", "长期"],
        reverse: '',
        positive: '',
        idpositive: '',
        idreverse: '',
        xszpositive:'',
        xszrevese:'',
        yyzgzpositive:'',
        clzppositive:'',
        jdkpositive:'',
        czczppositive:'',
        region_open:true,
        region:["吉林省",'长春市'],
        customItem: '全部'
    },
  edit(e){
    let that = this;
    app.Request({ url: 'driver/edit', method: 'post', data: {work_number: e.detail.value}}).then((res)=>{
      console.log(res)
      if (res.code == 1) {
        app.showToast(res.msg)
      }
    })
    console.log(e.detail.value)
  },
    //获取输入注册城市
  bindRegionChange:function(e){
    const {driver}=this.data;
    app.city = e.detail.value
    driver.city = e.detail.value;
    wx.setStorageSync("driverRegisterCity", e.detail.value);
    this.setData({ driver, region_open:true});
  },
    // selectNameHandler 输入姓名事件
    selectNameHandler: function() {
        const driver = this.data.driver;
        driver.name_status = true;
        this.setData({
            driver
        });
    },
    // 获取本地driver信息
    updateLocalDriver(key,value){
      let driver = wx.getStorageSync('mDriver') || {}
      console.log(driver)
      driver[key] = value
      wx.setStorageSync('mDriver',driver)
    },
    syncLocalDriver(){
      let _driver = wx.getStorageSync('mDriver') || {}
      let driver = this.data.driver
      Object.assign(driver,_driver)
      console.log(driver)
      this.setData({
        driver
      })

    },
    // selectedNameHandler 获取姓名事件
    selectedNameHandler: function(e) {
        // console.log(e,'name')
        const driver = this.data.driver;
        driver.name = e.detail.value;
        // this.setData({ driver });
        this.setData({
            driver
        })
        this.updateLocalDriver('name',e.detail.value)
    },
    // selectPhoneHandler 输入电话号码事件
    selectPhoneHandler: function() {
        const driver = this.data.driver;
        driver.phone_status = true;
        this.setData({
            driver
        });
        this.updateLocalDriver('phone_status',true)
    },
    // selectedPhoneHandler 获取电话号码
    selectedPhoneHandler: function(e) {
        const driver = this.data.driver;
        driver.phone = e.detail.value;
        this.setData({
            driver
        })
        this.updateLocalDriver('phone', e.detail.value)
    },
    // selectIdHandler 输入工号事件
    selectIdHandler: function() {
        const driver = this.data.driver;
        driver.id_status = true;
        this.setData({
            driver
        });
    },
    // selectedIdHandler 获取工号事件
    selectedIdHandler: function(e) {
        const driver = this.data.driver;
        driver.id = e.detail.value;
        driver.idTest = true;
        this.setData({
            driver
        });
        this.updateLocalDriver('id', e.detail.value)
        this.updateLocalDriver('idTest', true)

    },
    // selectNameHandler 输入联系人电话号码事件
    selectRelativeHandler: function() {
        const driver = this.data.driver;
        driver.relative_status = true;
        this.setData({
            driver
        });
        this.updateLocalDriver('relative_status', true)
    },
    // phoneTest 电话号码验证
    phoneTest: function(params) {
        if (params == '' || !/^1\d{10}$/.test(params)) {
            wx.showToast({
                title: '请输入正确的电话号码格式',
                icon: "none",
                duration:2000
            })
            return;
        } else {
            return true;
        }
    },
    // selectedNameHandler 获取联系人电话号码事件
    selectedRelativeHandler: function(e) {
        const driver = this.data.driver;
        driver.relative = e.detail.value;
        this.setData({
            driver
        });
        this.updateLocalDriver('relative', e.detail.value)
    },
    // selectNameHandler 输入银行卡号事件
    selectBankHandler: function() {
        const driver = this.data.driver;
        driver.bank_status = true;
        this.setData({
            driver
        });
        this.updateLocalDriver('bank_status',true)
    },
    // selectBankHandler 获取银行卡号事件
    selectedBankHandler: function(e) {
        const driver = this.data.driver;
        driver.bank = e.detail.value;
        this.setData({
            driver
        });
        this.updateLocalDriver('bank', e.detail.value)
    },
    bankTest: function(bankno) {
        var lastNum = bankno.substr(bankno.length - 1, 1); //取出 最后一位（与 luhm 进行比较） 
        var first15Num = bankno.substr(0, bankno.length - 1); // 前 15 或 18 位 
        var newArr = new Array();
        for (var i = first15Num.length - 1; i > -1; i--) {
            newArr.push(first15Num.substr(i, 1));
        }
        var arrJiShu = new Array(); //奇数位*2 的积 <9 
        var arrJiShu2 = new Array(); //奇数位*2 的积 >9 
        var arrOuShu = new Array(); //偶数位数组 
        for (var j = 0; j < newArr.length; j++) {
            if ((j + 1) % 2 == 1) {
                //奇数位 
                if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2);
                else arrJiShu2.push(parseInt(newArr[j]) * 2);
            } else arrOuShu.push(newArr[j]);
        }
        var jishu_child1 = new Array(); //奇数位*2 >9 的分割之 后的数组个位数 
        var jishu_child2 = new Array(); //奇数位*2 >9 的分割之 后的数组十位数 
        for (var h = 0; h < arrJiShu2.length; h++) {
            jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
            jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
        }
        var sumJiShu = 0; //奇数位*2 < 9 的数组之和 
        var sumOuShu = 0; //偶数位数组之和 
        var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组 个位数之和 
        var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组 十位数之和 
        var sumTotal = 0;
        for (var m = 0; m < arrJiShu.length; m++) {
            sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
        }
        for (var n = 0; n < arrOuShu.length; n++) {
            sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
        }
        for (var p = 0; p < jishu_child1.length; p++) {
            sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
            sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
        }
        //计算总和 
        sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);
        //计算 Luhm 值 
        var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
        var luhm = 10 - k;
        if (lastNum == luhm) {
            return true;
        } else {
            wx.showToast({
                title: '请输入正确的银行卡号',
                icon: "none",
                duration:2000
            })
            console.log("验证失败");
            return false;
        }
    },
    //选择驾驶证年龄
    getDriverAge:function(e){
      console.log(e)
      const {driver}=this.data;
      const driveTime =parseInt(e.detail.value)+1
      driver.driverTime=driveTime;
      console.log(driver.driverTime)
      this.setData({ driver})
      this.updateLocalDriver('driverTime', driveTime)
    },
     getDriverCate:function(e){
       const {driver}=this.data;
       const catindex =parseInt(e.detail.value)
       driver.cateindex= catindex;
       this.setData({ driver})
       this.updateLocalDriver('cateindex',catindex)
    },
    //getWorkAge:
    getWorkAge:function(){
      var arrayDriverAge = [];
      for (var i = 1; i <= 45; i++) {
        arrayDriverAge.push(i+'年')
      }
      this.setData({
        arrayDriverAge,
      });
    },
    // selectWorktimeHandler 输入工作年限事件
    selectWorktimeHandler: function(e) {
        console.log("selectWorktimeHandler");
        const driver = this.data.driver;
        driver.workTime_status = true;
        this.setData({
            driver,
            arrayDriverAge,
            driverAge: e.detail.value
        });
    },
    // selectedWorktimeHandler 获取银行卡号事件
    selectedWorktimeHandler: function(e) {
        const driver = this.data.driver;
        driver.workTime = e.detail.value;
        driver.workTimeTest = true;
        this.setData({
            driver
        });
    },
    // selectIdCardHandler 输入身份证事件
    selectIdCardHandler: function() {
        const driver = this.data.driver;
        driver.idCard_status = true;
        this.setData({
            driver
        });
    },
    // selectedIdHandler 获取身份证事件
    selectedIdCardHandler: function(e) {
        const driver = this.data.driver;
        driver.idCard = e.detail.value;
        this.setData({
            driver
        });
        this.updateLocalDriver('idCard',e.detail.value)
    },
    IdCardTest: function(idCard) {
        //15位和18位身份证号码的正则表达式
        var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
        //如果通过该验证，说明身份证格式正确，但准确性还需计算
        if (regIdCard.test(idCard)) {
            if (idCard.length == 18) {
                var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里
                var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
                var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
                for (var i = 0; i < 17; i++) {
                    idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
                }
                var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
                var idCardLast = idCard.substring(17); //得到最后一位身份证号码
                //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
                if (idCardMod == 2) {
                    if (idCardLast == "X" || idCardLast == "x") {
                        return true;
                    } else {
                        wx.showToast({
                            title: '身份证号码错误！',
                            icon: "none",
                            duration: 2000
                        })
                        return false;
                    }
                } else {
                    //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                    if (idCardLast == idCardY[idCardMod]) {
                        return true;
                    } else {
                        wx.showToast({
                            title: '身份证号码错误！',
                            icon: "none",
                            duration: 2000
                        })
                        return false;
                    }
                }
            }
        } else {
            wx.showToast({
                title: '身份证格式不正确！',
                icon: "none",
                duration: 2000
            })
            return false;
        }
    },
    // selectDriverAgeHandler 选择驾驶年龄
    selectDriverAgeHandler: function(e) {
        console.log(e.detail.value);
        const driver = this.data.driver;
        driver.driverTime = e.detail.value;
        this.setData({
            driver
        });
    },
    // selectDriverTimeHandler 选择驾驶证有效期年龄
    selectDriverTimeHandler: function(e) {
      console.log(e)
        // const driver = this.data.driver;
        // driver.driverTime_status = true;
        // this.setData({
        //     driver
        // });
    },
    // selectedDriverTimeHandler 选择驾驶证有效期年龄
    selectedDriverTimeHandler: function(e) {
        const {
            driver,
            driverEffictTime
        } = this.data;
        console.log(e.detail.value)
        driver.driverTime = driverEffictTime[e.detail.value];
        this.setData({
            driver
        });
    },
    //获取驾驶证有效期
    /**
     * 开始时间
     * 结束时间
     */
    startEfficeTime:function(e){
      console.log(e)
      const { driver}=this.data;
      driver.driverTime_start= e.detail.value;
      this.setData({ driver})
      this.updateLocalDriver('driverTime_start',e.detail.value)
    },  
    endEfficeTime:function(e){
      console.log(e)
      const { driver } = this.data;
      driver.driverTime_end = e.detail.value;
      this.setData({ driver })
      this.updateLocalDriver('driverTime_end',e.detail.value)
    },
    // intoPageHandler 页面跳转
    intoPageHandler: function(e) {
        var that = this;
        //var jsonstr = JSON.stringify(that.data.driver)
        wx.setStorageSync("driverss", that.data.driver);
        wx.navigateTo({
          url: e.currentTarget.dataset.skip,
        })
       
    },
    // personalInformationHandler 完成按钮 提交个人信息
    personalInformationHandler: function() {
        var that = this;
        console.log('获取所有信息', this.data.driver);
        const driver = this.data.driver;
        wx.showLoading({})
        console.log(driver,'认证信息')
        app.request({
            url: api.driver.information,
            method: 'post',
            data: {
                city: that.data.driver.city, //城市 region
                name: that.data.driver.name, //银行卡号
                phone: that.data.driver.phone, //银行卡号
                id: that.data.driver.id, //银行卡号
                relative: that.data.driver.relative, //银行卡号
                bank: that.data.driver.bank, //银行卡号
                workTime: that.data.driver.driverTime, //银行卡号
                idCard: that.data.driver.idCard, //银行卡号
                driverTime_end:that.data.driver.driverTime_end,
                driverTime_start: that.data.driver.driverTime_start,
                cateid: that.data.driver.cateindex,//分类 0是代驾 1是出租车
                catename: that.data.driver.arrayDrivercate[that.data.driver.cateindex],//分类名字
                //银行卡号
                idCardPhoto: wx.getStorageSync("idpositive"), //银行卡号
                idreverse: wx.getStorageSync("idreverse"), //银行卡号
                driverPhoto: wx.getStorageSync("positive"), //驾照正面照片
                reverse: wx.getStorageSync("reverse"), //驾照反面照片
                xszz: wx.getStorageSync("xszpositive"), //驾照反面照片
                xszf: wx.getStorageSync("xszreverse"), //驾照反面照片
                clzp: wx.getStorageSync("clzppositive"), //驾照反面照片
                yyzgz: wx.getStorageSync("yyzgzpositive"), //驾照反面照片
                jdk: wx.getStorageSync("jdkpositive"), //驾照反面照片
                czczp: wx.getStorageSync("czczppositive"), //驾照反面照片
                access_token: wx.getStorageSync('access_token'),

            },
            success: function(rss) {
              wx.hideLoading()
                if (rss.code == 1) {
                  
                  wx.showModal({
                    title: '提示',
                    content: rss.msg,
                    showCancel:false,
                    success: function () {
                      if (wx.canIUse('requestSubscribeMessage')) {
                        app.request({
                          url: api.message.getTmplIds,
                          method: "GET",
                          data: {
                            type: 3
                          },
                          success: res => {
                            wx.requestSubscribeMessage({
                              tmplIds: res.data,
                              complete: res => {
                                console.log(res)
                              }
                            })
                          }
                        })
                      }
                      setTimeout(function () {
                        wx.navigateBack({
                          delta: 2
                        })
                      }, 1500)
                    }
                  })
                  // wx.showToast({
                  //   title: rss.msg,
                  //   icon: "none",
                  //   success: function () {
                  //     setTimeout(function(){
                  //       wx.navigateBack({
                  //         delta: 2
                  //       })
                  //     },1500)
                  //   }
                  // })
                    // wx.setStorageSync("user_type", "driver")
                    // wx.redirectTo({
                    //   url: '/pages/driver/userauth-pay/index',
                    // })
                    // wx.redirectTo({
                    //   url: "../../index/index",
                    // })
                    // handler.intoPageHandler()
                } else {
                  wx.showToast({
                      title: rss.msg,
                      duration: 2000,
                      icon:"none",
                  })
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (typeof(options.type) != 'undefined') {
            if (typeof(options.positive) != 'undefined') {
                this.setData({
                    positive: wx.getStorageSync("positive")
                });
            }
            if (typeof(options.reverse) != 'undefined') {
                this.setData({
                    reverse: wx.getStorageSync("reverse")
                });
            }
            if (typeof(options.reverse) != 'undefined') {
                this.setData({
                    idreverse: wx.getStorageSync("idreverse")
                });
            }
            if (typeof(options.positive) != 'undefined') {
                this.setData({
                    idpositive: wx.getStorageSync("idpositive")
                });
            }
        } else {
            wx.removeStorageSync('driverss')
        }
        //获取驾龄
      this.getWorkAge();
      // 获取优惠券
      if (options.uid) {
        app.shareCouponsMessage(options.uid)
      }
      // 同步driver信息
      this.syncLocalDriver()
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let that = this;
        let drived = wx.getStorageSync("driverss");
        // const driver = that.data.driver;
        let { driver}=this.data;
        // app.request({
        //     url: api.driver.getinformation,
        //     method: 'post',
        //     data: {},
        //     success: function(rs) {
        //       console.log(rs)
        //       console.log('zcj3')
        //         if (rs.code == 1) {
        //             wx.setStorageSync('driving_license',rs.data.driving_license)
        //             wx.setStorageSync('id_card_pic',rs.data.id_card_pic)
        //           //缓存身份证照
        //           wx.setStorageSync('idpositive', rs.data.id_card_pic.id_card_pic)
        //           wx.setStorageSync('idreverse', rs.data.id_card_pic.id_card_fpic)
        //           //缓存驾驶证照
        //           wx.setStorageSync('positive', rs.data.driving_license.driverPhoto)
        //           wx.setStorageSync('reverse', rs.data.driving_license.driverfPhoto)
        //           //缓存行驶证证照
        //           wx.setStorageSync('xszpositive', rs.data.xszz)
        //           wx.setStorageSync('xszreverse', rs.data.xszf)
        //           wx.setStorageSync('clzppositive', rs.data.clzp)
        //           wx.setStorageSync('yyzgzpositive', rs.data.yyzgz)
        //           wx.setStorageSync('czczppositive', rs.data.czczp)
        //           wx.setStorageSync('jdkpositive', rs.data.jdk)
        //           //添加数据
        //             driver.city = rs.data.city;//城市
        //             var region_open=!rs.data.city.length == 0;
        //             driver.name = rs.data.real_name;//昵称
        //             driver.phone = rs.data.work_phone;//电话
        //             driver.id = rs.data.id; //工号
        //             driver.relative = rs.data.emergency; //紧急联系人
        //             driver.bank = rs.data.bank; //银行卡号
        //             driver.idCard = rs.data.id_card; //身份证号
        //             // 身份证照
        //             driver.idCardPhotoTest={
        //               idpositive: rs.data.id_card_pic.id_card_pic, 
        //               idreverse: rs.data.id_card_pic.id_card_fpic
        //             }
        //             //证件照
        //             driver.driverPhotoTest={
        //               positive: rs.data.driving_license.driverPhoto,
        //               reverse: rs.data.driving_license.driverfPhoto
        //             };
        //             driver.xszz = rs.data.xszz;
        //             driver.xszf = rs.data.xszf;
        //             driver.clzp = rs.data.clzp;
        //             driver.cateindex = rs.data.cateid;
        //             driver.yyzgz = rs.data.yyzgz;
        //             driver.czczp = rs.data.czczp;
        //             driver.jdk = rs.data.jdk;
        //             // 是否已上传照片
        //             driver.driverTime = rs.data.been_driving; 
        //             driver.driverTime_end= rs.data.period[0];
        //             driver.driverTime_start = rs.data.period[1];
                    
        //             that.setData({
        //               driver, region_open, audit: rs.data.audit
        //             });
        //         } else {
        //           driver.city = app.city;
        //           driver.idCardPhotoTest = { idpositive: wx.getStorageSync("idpositive"), idreverse: wx.getStorageSync("idreverse")};
        //           driver.driverPhotoTest = { positive: wx.getStorageSync("positive"), reverse: wx.getStorageSync("reverse") };
        //           driver.xszz = wx.getStorageSync("xszpositive");
        //           driver.xszf = wx.getStorageSync("xszreverse");
        //           driver.clzp = wx.getStorageSync("clzppositive");
        //           driver.yygzz = wx.getStorageSync("yyzgzpositive");
        //           driver.jdk = wx.getStorageSync("jdkpositive");
        //           driver.czczp = wx.getStorageSync("czczppositive");
        //           console.log(wx.getStorageSync("idpositive"), '----app.city')
        //           console.log(app.city,'----app.city')

        //           that.setData({
        //             driver
        //           })
                  
        //         }
                // 判断用户是否可以修改数据
        //       if (rs.code == 1 && rs.data.audit==1){
        //         that.setData({isChange:true})
        //       }else{
        //         that.setData({ isChange: false })
        //       }
               
        //     }
        // })
    },
  // 用户分享
  onShareAppMessage: function () {
    let title = app.shareAppMessage().title;
    let imageUrl = app.shareAppMessage().imageUrl;
    let desc = app.shareAppMessage().desc;
    let path = app.shareAppMessage().path;
    console.log(app.shareAppMessage())
    return {
      title: title,
      imageUrl: imageUrl,
      desc: desc,
      path: path,
    }
  },
})